package com.ml4ai.backend.security;

import com.ml4ai.backend.domain.Role;
import com.ml4ai.backend.domain.User;
import com.ml4ai.backend.dto.AuthorityDTO;
import com.ml4ai.backend.dto.RoleDTO;
import com.ml4ai.backend.dto.UserAgent;
import com.ml4ai.backend.dto.UserDTO;
import com.ml4ai.backend.repository.UserRepo;
import com.ml4ai.backend.services.AuthorityService;
import com.ml4ai.backend.services.RoleService;
import com.ml4ai.backend.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by uesr on 2018/9/8.
 */
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    AuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        UserDTO queryUser = new UserDTO();
        queryUser.setStatus("1");
        queryUser.setLogin(s);
        List<UserDTO> users = userService.query(queryUser);

        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("非法用户");
        } else if (users.size() == 1) {
            UserDTO user = users.get(0);
            RoleDTO queryRole = new RoleDTO();
            queryRole.setStatus("1");
            queryRole.setUserId(user.getId());
            List<RoleDTO> roles = roleService.query(queryRole);
            UserAgent u = new UserAgent(user, roles.stream().flatMap(role -> {
                AuthorityDTO queryAuthority = new AuthorityDTO();
                queryAuthority.setStatus("1");
                queryAuthority.setRoleId(role.getId());
                List<AuthorityDTO> authorityDTOS = authorityService.query(queryAuthority);
                return authorityDTOS.stream();
            }).map(GrantedAuthority::getAuthority).map(SimpleGrantedAuthority::new).collect(Collectors.toList()), true, true, true, true);
            return u;
        } else {
            throw new IllegalStateException("该用户有多个请联系工作人员[" + s + "]");
        }
    }

}
